<?php
namespace app\admin\model;

use think\Model;
use think\Session;


class QClass extends Model
{

    

    

    // 表名
    protected $name = 'child_q_class';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'delete_time_text',
        'update_time_text'
    ];
    

    



    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getDeleteTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['delete_time']) ? $data['delete_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setDeleteTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    //获取分类id和名称
    public  function getClassName(){
        return $this->field(['q_class_id','name'])->where('delete_time','=',0)->select();
    }

    public function QFormat(){
        return $this->hasMany('QuestionFormat','q_class_id',"q_class_id")->where('delete_time','0')
        ->field(['id','q_class_id','name','available',
            'show_mode','full_mark','pass_mark','is_automatic','count','code_url','create_time']);
    }

    //获取分类列表(onlyAvailable是否只显示激活)
    public function getQuestionnaireClassList($onlyAvailable=false)
    {

        $group_arr = Session::get('admin_group_arr');
        $where = ['delete_time'=>0];
        if(!in_array(1,$group_arr)){
            $where['uid'] =  Session::get('admin')['id'];
        }
        
        $result= $this->with('QFormat')
        ->where($where)
        ->paginate(0, false, [
            'query' => \request()->request()
        ]);
        // if($onlyAvailable){
        //     foreach ($result as $value){
        //         foreach ($value['q_format'] as $k=>$v){
        //             if($v['available']==0){
        //                 unset($value['q_format'][$k]);
        //             }
        //         }

        //     }
        // }
        return $result;


    }
}
